<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/8
 * Time: 13:44
 */

namespace common\business\mdm;


use common\business\DbHandler;
use common\business\EhrHelper;
use common\consts\CommonResources;
use common\helpers\StringUtil;
use common\models\kingdee\OrgAdmin;
use common\models\mdm\MdmDept;
use common\models\mdm\MdmOrg;
use common\result\ActionResult;
use yii\helpers\Json;

class MdmDeptService extends DbHandler
{
    /**
     * @var string
     */
    protected $_department_code;
    public function setDepartmentCode($department_code){
        $this->_department_code = $department_code;
    }

    /**
     * @var OrgAdmin
     */
    protected $_topOrg;
//    /**
//     * @var MdmOrg
//     */
//    protected $_topMdmOrg;
    /**
     * @var MdmDept
     */
    protected $_topMdmDept;
//    /**
//     * @var boolean
//     */
//    protected $_topIsCompany;

    /**
     * @param callback|null $writeBackHandler
     * @return ActionResult
     */
    public function sync($writeBackHandler = null) {
        $apiHandler = new MdmApiHandler();

        $totalResult = new ActionResult();
        $isSyncTopSuccess = $this->syncTopOrgAndTopMdmDept($totalResult, $writeBackHandler);
        if (!$isSyncTopSuccess){
            return new ActionResult(false, CommonResources::ACTION_FAIL_MSG('Sync', 'Department', $this->getErrorsMessage()));
        }

        $this->syncChildrenWithParentDepartment($this->_topOrg, $this->_topMdmDept, $totalResult, $writeBackHandler);
        return $totalResult;
    }

    /**
     * 需要找到最顶层Org，并且寻找企业微信是是否有这个节点，如果名字不一样要更新
     * @param $totalResult ActionResult
     * @param callback|null $writeBackHandler
     * @return bool
     */
    protected function syncTopOrgAndTopMdmDept($totalResult, $writeBackHandler = null){
        $topIsRoot = false;
        $apiHandler = new MdmHandler();
        $apiHandler->setCrud(new MdmDeptCrud());

        $isSkipped = false;

        if(!StringUtil::isNullOrWhiteSpace($this->_department_code)){
            $this->_topOrg = OrgAdmin::findOne([
                'FNUMBER' => $this->_department_code,
            ]);
            $topIsRoot = false;

            if ($this->_topOrg->FPARENTID == null){
            }
            else {
                $topParentOrg = OrgAdmin::findOne([
                    'FID' => $this->_topOrg->FPARENTID,
                ]);
                $topParentDepartment = MdmDept::findOne(['DEPARTMENTCODE' => $topParentOrg->FNUMBER]);
            }
        }
//        否则拿顶层节点
        else{
            $this->_topOrg = OrgAdmin::findOne([
                'FPARENTID' => null,
            ]);
            $topIsRoot = true;
        }

        if (!$this->_topOrg)
        {
            $this->addError('Find Top Mdm Dept', 'Top Mdm Dept Not Found');
            $totalResult->addSubResult(new ActionResult(false, $this->getErrorsMessage()));
            $this->executeWriteBackHandlerNoTotal($totalResult, $writeBackHandler);
            return false;
        }

//        if (EhrHelper::checkIsCompany($this->_topOrg)){
//            $this->_topMdmOrg = MdmOrg::findOne([
//                'ORGNAME' => $this->_topOrg->FNAME_L2,
//                'BILLCODE' => $this->_topOrg->FNUMBER,
//            ]);
//            $this->_topIsCompany = true;
//        }
//        else {
//            MdmDept::deleteAll(
//                'DEPARTMENTCODE=:code and DEPARTMENTNAME<>:name',
//                [
//                    ':code' => $this->_topOrg->FNUMBER,
//                    ':name' => $this->_topOrg->FNAME_L2,
//                ]
//            );
//
//            $this->_topMdmDept = MdmDept::findOne([
//                'DEPARTMENTCODE' => $this->_topOrg->FNUMBER,
//                'DEPARTMENTNAME' => $this->_topOrg->FNAME_L2,
//            ]);
//            $this->_topIsCompany = false;
//        }

        MdmDept::deleteAll(
            'DEPARTMENTCODE=:code and DEPARTMENTNAME<>:name',
            [
                ':code' => $this->_topOrg->FNUMBER,
                ':name' => $this->_topOrg->FNAME_L2,
            ]
        );
        $this->_topMdmDept = MdmDept::findOne([
            'DEPARTMENTCODE' => $this->_topOrg->FNUMBER,
            'DEPARTMENTNAME' => $this->_topOrg->FNAME_L2,
        ]);

//        if ($this->_topIsCompany){
//            if (!$this->_topMdmOrg){
//                $totalResult->addSubResult(new ActionResult(false, CommonResources::ACTION_NAME_MODEL_FAIL_WITH_REASON('syncTopOrgAndTopMdmDept', 'MdmOrg', $topOrg->FNAME_L2, 'Top Org is not existed.')));
//                $this->executeWriteBackHandlerNoTotal($totalResult, $writeBackHandler);
//                return false;
//            }
//        }
//        else {
//            if (!$this->_topMdmDept){
//                $this->_topMdmDept = EhrHelper::createOrUpdateMdmDeptByOrgAdmin($this->_topOrg);
//
//                $createResult = $handler->create($this->_topMdmDept);
//                if (!$createResult->isSuccess){
//                    $totalResult->addSubResult($createResult);
//                    $this->executeWriteBackHandlerNoTotal($totalResult, $writeBackHandler);
//                    return false;
//                }
//            }
//        }

        if (!$this->_topMdmDept){
            $this->_topMdmDept = EhrHelper::createOrUpdateMdmDeptByOrgAdmin($this->_topOrg);
            $createResult = $apiHandler->create($this->_topMdmDept);
            if (!$createResult->isSuccess){
                $totalResult->addSubResult($createResult);
                $this->executeWriteBackHandlerNoTotal($totalResult, $writeBackHandler);
                return false;
            }
        }

//        if ($this->_topIsCompany){
//            $this->_topMdmOrg = MdmOrg::findOne([
//                'ORGNAME' => $this->_topOrg->FNAME_L2,
//                'BILLCODE' => $this->_topOrg->FNUMBER,
//            ]);
//        }
//        else {
//
//        }
        $this->_topMdmDept = MdmDept::findOne([
            'DEPARTMENTCODE' => $this->_topOrg->FNUMBER,
            'DEPARTMENTNAME' => $this->_topOrg->FNAME_L2,
        ]);
//更新属性
        EhrHelper::createOrUpdateMdmDeptByOrgAdmin($this->_topOrg, $this->_topMdmDept);
        $oldObj = MdmDept::findOne([
            'DEPARTMENTCODE' => $this->_topOrg->FNUMBER,
            'DEPARTMENTNAME' => $this->_topOrg->FNAME_L2,
        ]);
        $updateResult = $apiHandler->update($this->_topMdmDept, $oldObj, ['PK_DEPARTMENT', 'DEPARTMENTCODE', 'DEPARTMENTNAME', 'SSORG', 'PK_DEF1']);
        if (!$updateResult->isSuccess){
            $totalResult->addSubResult($updateResult);
            $this->executeWriteBackHandlerNoTotal($totalResult, $writeBackHandler);
            return false;
        }
        if ($updateResult->isSkipped)
            $isSkipped = true;

        $totalResult->addSubResult(new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG('Sync Top', 'MdmDept'), $isSkipped));
        $this->executeWriteBackHandlerNoTotal($totalResult, $writeBackHandler);
        return true;
    }

    /**
     * @param $parentOrg OrgAdmin
     * @param $parentMdmDept MdmDept
     * @param $totalResult ActionResult
     * @param callback|null $writeBackHandler
     */
    protected function syncChildrenWithParentDepartment($parentOrg, $parentMdmDept, $totalResult, $writeBackHandler = null){
//        $apiHandler = new DepartmentApiHandler();
        $apiHandler = new MdmHandler();
        $apiHandler->setCrud(new MdmDeptCrud());

        $childrenOrgs = OrgAdmin::findAll([
            'FPARENTID' => $parentOrg->FID,
        ]);
        if (sizeof($childrenOrgs) == 0){
            return;
        }
        foreach ($childrenOrgs as $childOrg){
            $childMdmDept = $this->syncSingleOrgWithParent($childOrg, $parentMdmDept, $totalResult, $writeBackHandler);
            if ($childMdmDept){
                $this->syncChildrenWithParentDepartment($childOrg, $childMdmDept, $totalResult, $writeBackHandler);
            }
        }
    }

    /**
     * @param $org OrgAdmin
     * @param $parentMdmDept MdmDept
     * @param $totalResult ActionResult
     * @param callback|null $writeBackHandler
     * @return MdmDept
     */
    protected function syncSingleOrgWithParent($org, $parentMdmDept, $totalResult, $writeBackHandler = null){
        $isSkipped = false;
        $apiHandler = new MdmHandler();
        $apiHandler->setCrud(new MdmDeptCrud());

//        Department::deleteAll(
//            'number=:number and name<>:name',
//            [
//                ':number' => $parentDepartment->number,
//                ':name' => EhrHelper::getName4QywxDepartment($org),
//            ]
//        );
//        保险起见全部删掉重建
        MdmDept::deleteAll([
            'DEPARTMENTCODE' => $org->FNUMBER,
        ]);

        $mdmDeptInDb = MdmDept::findOne([
            'DEPARTMENTCODE' => $org->FNUMBER,
            'PK_DEF1' => $parentMdmDept->PK_DEPARTMENT,
        ]);

        if (!$mdmDeptInDb){
            $newMdmDept = EhrHelper::createOrUpdateMdmDeptByOrgAdmin($org);
            $createResult = $apiHandler->create($newMdmDept);
            if (!$createResult->isSuccess){
                $totalResult->addSubResult($createResult);
                $this->executeWriteBackHandlerNoTotal($totalResult, $writeBackHandler);
                return null;
            }

            $mdmDeptInDb = MdmDept::findOne([
                'DEPARTMENTCODE' => $org->FNUMBER,
                'DEPARTMENTNAME' => $org->FNAME_L2,
            ]);
        }

        //状态变成更新中
        EhrHelper::createOrUpdateMdmDeptByOrgAdmin($org, $mdmDeptInDb);
        $oldObj = MdmDept::findOne([
            'DEPARTMENTCODE' => $org->FNUMBER,
            'DEPARTMENTNAME' => $org->FNAME_L2,
        ]);
        $updateResult = $apiHandler->update($mdmDeptInDb, $oldObj, ['PK_DEPARTMENT', 'DEPARTMENTCODE', 'DEPARTMENTNAME', 'SSORG', 'PK_DEF1']);
        if (!$updateResult->isSuccess){
            $totalResult->addSubResult($updateResult);
            $this->executeWriteBackHandlerNoTotal($totalResult, $writeBackHandler);
            return null;
        }
        if ($updateResult->isSkipped)
            $isSkipped = true;

        $totalResult->addSubResult(new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG('Sync Single', 'MdmDept'), $isSkipped));
        $this->executeWriteBackHandlerNoTotal($totalResult, $writeBackHandler);
        return $mdmDeptInDb;
    }
}